package com.beyondbit.demo.common;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.boot.jackson.JsonComponent;

import java.util.Date;


@JsonComponent
public class JsonDateDeserializer extends JsonDeserializer<Date> {

    private static final String[] DATE_PATTERNS = {"yyyy-MM", "yyyy-MM-dd", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH:mm:ss", "HH:mm"};

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) {
        Date parseDate;

        try {
            String dateAsString = jsonParser.getText();

            if (StringUtils.isBlank(dateAsString)) {
                return null;
            }

            parseDate = DateUtils.parseDate(dateAsString, DATE_PATTERNS);
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getCause());
        }

        return parseDate;
    }
}